package com.atguigu.tms.mock.task;

import com.atguigu.mock.util.RandomBox;
import com.atguigu.tms.mock.bean.*;
import com.atguigu.tms.mock.constant.TmsConstant;
import com.atguigu.tms.mock.service.OrderInfoService;
import com.atguigu.tms.mock.service.OrderTraceLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.atguigu.tms.mock.constant.TmsConstant.TASK_TYPE_COLLECT;

@Component
@Slf4j
public class SignOrderTask {

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    OrderTraceLogService orderTraceLogService;

    //检查送达的订单
    //低概率判断是否签单
    //如果3天美哟签收 则确定签收
    public void doSign(Date curDate){
        List<OrderInfo> orderInfoDelieveredList = orderInfoService.list(new QueryWrapper<OrderInfo>().eq("status", TmsConstant.ORDER_STATUS_DELIVERED));
        log.warn("待签收 : 共 {} 件",orderInfoDelieveredList.size() );
        RandomBox ifSignedBox = new RandomBox(10, 90);
        List<OrderInfo> orderInfoSignedList=new ArrayList<>();
        for (OrderInfo orderInfo : orderInfoDelieveredList) {
            Date updateTime = orderInfo.getUpdateTime();
            if(  DateUtils.addDays(updateTime,+3).before(curDate)){
                signOrder(  orderInfo,  curDate);
                orderInfoSignedList.add(orderInfo);
                genOrderTraceLogDelivered(  orderInfo );
            }else if(ifSignedBox.getRandBoolValue()){
                signOrder(  orderInfo,  curDate);
                genOrderTraceLogDelivered(  orderInfo );
                orderInfoSignedList.add(orderInfo);
            }
        }
        orderInfoService.saveOrUpdateBatch(orderInfoSignedList,1000,true);


    }

    private void  signOrder(OrderInfo orderInfo,Date curDate){
        orderInfo.setStatus(TmsConstant.ORDER_STATUS_SIGNED);
        orderInfo.setUpdateTime(curDate);

    }

    public void genOrderTraceLogDelivered(OrderInfo orderInfo ){
        OrderTraceLog orderTraceLog = new OrderTraceLog();
        orderTraceLog.setOrderId(orderInfo.getId());


        orderTraceLog.setTraceDesc("您的快件已签收");
        orderTraceLog.setCreateTime(orderInfo.getUpdateTime());

        orderTraceLog.setIsDeleted("0");
        orderTraceLogService.saveOrUpdate(orderTraceLog );
    }

}
